package br.com.project.webservice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;
import br.com.project.entity.Simulation;
import br.com.project.entity.Student;
import br.com.project.exception.CouldNotConnectException;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class WSClient {

	private ClientConfig config;
	private Client client;
	private WebResource service;
	
	private String url = "http://192.168.0.132:8080/BizzWeb/rest";
	
	public WSClient(){
		config = new DefaultClientConfig();
		client = Client.create(config);
		service = client.resource(getBaseURI());
	}
	
	public URI getBaseURI(){
		return UriBuilder.fromUri(url).build();
	}
	
	public void hello(){
		service.path("web").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
	}
	
	public Student login(){
		Student student = new Student();
		student.setId(1);
		student.setLogin("jumaialeite");
		student.setName("Juliana Maia Leite");
		student.setPassword("123456");
		
		return student;
//		 String result = getRESTFileContent(url+"/login/juliana#maia"); 
//		 System.out.println(result);
		
//		ClientResponse response = service.path("web").path("login").path("juliana").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
//		int status = response.getStatus();
//		String textEntity = response.getEntity(String.class);
//		
//		System.out.println(status+" - "+textEntity);
		
	}
	
	public List<Simulation> getSimulationList() throws CouldNotConnectException{
		
		String uri = url+"/web/simulations";
		
		Gson gson = new Gson();
		String result = getRESTFileContent(uri);
		
		String subs = result.substring(14, result.length()-1);
		
		Type type = new TypeToken<List<Simulation>>(){}.getType();
		List<Simulation> simulationList = gson.fromJson(subs, type);

        for (Simulation simulation : simulationList) {
            System.out.println("ID - Title = " + simulation.getId() + " - " + simulation.getTitle());
        }
        
        return simulationList;
	}
	
	public InputStream getJSONData(String url) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		URI uri;
		InputStream data = null;
		try {
			uri = new URI(url);
			HttpGet method = new HttpGet(uri);
			HttpResponse response = httpClient.execute(method);
			data = response.getEntity().getContent();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return data;
	}
	
	public String getRESTFileContent(String url) throws CouldNotConnectException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);

		try {
			HttpResponse response = httpclient.execute(httpget);

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = toString(instream);

				instream.close();
				return result;
			}
		} catch (Exception e) {
			Log.e("NGVL", "Falha ao acessar Web service", e);
			throw new CouldNotConnectException();
		}
		return null;
	} 

	public String toString(InputStream is) throws IOException {

		byte[] bytes = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int lidos;
		while ((lidos = is.read(bytes)) > 0) {
			baos.write(bytes, 0, lidos);
		}
		return new String(baos.toByteArray());
	} 
	
}

//		try {
//			JSONObject json = new JSONObject(result);
//			JSONArray nameArray = json.names();
//			
//			JSONArray simulationsArray =  json.toJSONArray(nameArray);
//			
//			JSONObject simulationJson;
//			
//			for (int i = 0; i < simulationsArray.length(); i++) {
//				
//				simulationJson = new JSONObject(simulationsArray.getString(i));
//				
//				Simulation simulation = new Simulation();
//				simulation.setId(simulationJson.getInt("id"));
//				simulation.setDescription(simulationJson.getString("description"));
//				simulation.setTitle(simulationJson.getString("title"));
//
//				System.out.println("------------------------");
//				System.out.println("description=" + simulation.getDescription());
//				System.out.println("id=" + simulation.getId());
//				System.out.println("nome=" + simulation.getTitle());
//				
//				JSONArray nameQuestionArray = new JSONArray();
//				nameQuestionArray.put("questions");
//				System.out.println("->>>> "+nameQuestionArray);
//				
//				JSONArray questionsArray =  simulationJson.toJSONArray(nameQuestionArray);
//				System.out.println("->>>> "+questionsArray);
//				
//				JSONObject questionJson;
//				
//				for (int j = 0; j < questionsArray.length(); j++) {
//					questionJson = new JSONObject(questionsArray.getString(j));
//					System.out.println("question "+j+" - " + questionJson.getString("question"));
//					
//					JSONArray nameAnswerArray = new JSONArray();
//					nameAnswerArray.put("answers");
//					
//					System.out.println("->>>> "+nameAnswerArray);
//					
//					JSONArray answersArray = questionJson.toJSONArray(nameAnswerArray);
//					System.out.println("->>>> "+answersArray);
//					
//					JSONObject answerJson;
//					
//					for (int k = 0; k < answersArray.length(); k++) {
//						answerJson = new JSONObject(answersArray.getString(k));
//						System.out.println("answer "+j+" - " + answerJson.getString("answer"));
//					}
//				}
//				
////				System.out.println("questions=" + simulationJson.getJSONArray("questions"));
//			}   
//			
//			
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}  